package com.ktjy.ktmall.dao.impl;

import com.ktjy.ktmall.dao.BaseDao;
import com.ktjy.ktmall.dao.SkuItemDao;
import com.ktjy.ktmall.entity.SkuItem;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @version v1.0
 * @Author 郴州科泰
 * @Create 2024-07-23 - 21:19
 */
public class SkuItemDaoImpl extends BaseDao implements SkuItemDao {
    /**
     * 根据商品id查询此商品的SKU列表
     * @param goodsId 商品id
     * @return 返回当前商品id
     */
    @Override
    public List<SkuItem> findByGoodsId(int goodsId) {
        List<SkuItem> list = new ArrayList<>();
        String sql = "select * from t_sku_info where goods_id=?";
        rs = super.executeQuery(sql, goodsId);
        try {
            while (rs.next()) {
                SkuItem sku = new SkuItem(rs.getInt("id"),rs.getInt("goods_id"), rs.getString("stock_sku"), rs.getBigDecimal("price"), rs.getBigDecimal("old_price"),rs.getLong("inventory"), rs.getString("picture"));
                list.add(sku);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return list;
    }

    /**
     * 通过主键id查询商品SKU的详情信息
     * @param id 主键id
     */
    @Override
    public SkuItem findById(int id) {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Connection conn = this.getConnection();
        SkuItem sku = null;
        String sql = "select * from t_sku_info where `id` = ?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setObject(1, id);
            rs = pstmt.executeQuery();

            while (!rs.isClosed() && rs.next()) {
                sku = new SkuItem(rs.getInt("id"),rs.getInt("goods_id"), rs.getString("stock_sku"), rs.getBigDecimal("price"), rs.getBigDecimal("old_price"),rs.getLong("inventory"), rs.getString("picture"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            super.closeAll(rs, pstmt, conn);
        }
        return sku;
    }
}
